import numpy as np
import os  
from sklearn.metrics import confusion_matrix
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotlib.pyplot as plt
import pylab as pl
import plotly.express as px
import plotly.graph_objs as go
import plotly.figure_factory as ff
import plotly.io as pio
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

px_xaxis = {'linecolor': 'black', 'linewidth': 5,
               'gridcolor': 'grey', 'gridwidth': 5}

px_yaxis = {'linecolor': 'black', 'linewidth': 5,
               'gridcolor': 'grey', 'gridwidth': 5}

#X是数量，Y是am占比
def scatter2d(X, Y, mid_point, label, with_title):
    plt.figure(figsize=(6, 4))
    if with_title:
        plt.title(label)
#    plt.xlim(-100, 100)
#    plt.ylim(-100, 100)
    plt.scatter(X[0:mid_point], Y[0:mid_point], c='cornflowerblue', alpha=0.5, s=8, label='Training')
    plt.scatter(X[mid_point:-1], Y[mid_point:-1], c='orange', alpha=0.5, s=8, label='Generated')
    plt.legend(loc='upper left', fontsize=13)
    plt.savefig('pic/'+label+'.png', bbox_inches = 'tight')
    plt.show()

def scatter2d_1(X, Y):
    plt.figure(figsize=(6, 6))
    plt.xlim(-4, 4)
    plt.ylim(-4, 4)
    plt.scatter(X, Y, c='cornflowerblue', alpha=0.5, label='Training')
    plt.legend(loc='upper left', fontsize=13)
    plt.plot([-4, 4], [-4, 4], linestyle='dashed', color='black')
    plt.show()

def scatter3d(X, Y, Z, mid_point):
    fig = plt.figure(figsize=(6, 4))
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(X[0:mid_point], Y[0:mid_point], Z[0:mid_point], c='cornflowerblue', alpha=0.5, s=3, label='Real')
    ax.scatter(X[mid_point:-1], Y[mid_point:-1], Z[mid_point:-1], c='orange', alpha=0.5, s=3, label='Generated')
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')
    plt.legend(loc='best')
    plt.savefig('pic/3d.pdf')
   # plt.show()

def ternary_scatter_px(xt, xg, alloy):
    Y = []
    for i in range(len(xt)):
        Y.append('Test')
    for i in range(len(xg)):
        Y.append('Generated')
    Y = np.array(Y)
    X = np.vstack((xt, xg))

    x0 = X[:,0]
    x1 = X[:,1]
    x2 = X[:,2]
   # Y = Y.squeeze()
    print(x0.shape)
    print(x1.shape)
    print(x2.shape)
    print(Y.shape)
    df = pd.DataFrame({alloy[0]:x0, alloy[1]:x1, alloy[2]:x2, "Type": Y})
    fig = px.scatter_ternary(df, a=alloy[0], b=alloy[1], c=alloy[2],
            size = [1]*len(Y),
            opacity = 0.5,
            color='Type', width=1080, height=1080,
            color_discrete_sequence = px.colors.qualitative.T10                                         
            )
    fig.update_layout(
        template="plotly_white", font={'color': 'black', 'size': 50},
        margin=dict(l=100, r=100, t=30, b=20),
        legend_title_text=" ",                     
        legend=dict(
            yanchor="top",
            y=0.99,
            xanchor="left",
            x=0.01),
        ternary =  {
            'sum': 100,
            'aaxis': px_xaxis,
            'baxis': px_xaxis,
            'caxis': px_xaxis
        },
       )
    pio.show(fig)
    pio.write_image(fig, "pic/" + ''.join(alloy) + ".png")


def group_histogram1():
    x = np.array(['B', 'P', 'S', 'Si', 'C', 'F', 'H', 'Total', 'B', 'P', 'S', 'Si', 'C', 'F', 'H', 'Total'])
    y = [0.59, 0.27, 0.27, 0.85, 0.25, 0.2, 0.5392, 0.85, 0.497, 0.263, 0.0124, 0.841, 0.202, 0.00, 0.409, 0.841]
    c = np.hstack((np.full(8, 'Training'), np.full(8, 'Generated')))
    df = pd.DataFrame({'Non-metallic elements': x, 'Maximum atomic percentage': y, "Type": c})
    fig = px.bar(data_frame=df,
          #       title="Sample size",  # 图的标题
                 x='Non-metallic elements',
                 y='Maximum atomic percentage',  # y轴
                 color="Type",
                 width=1200, height=700,
                 barmode='group',
                 color_discrete_sequence=px.colors.qualitative.T10
                 )

    fig.update_layout(
        #title='Maximum non-metallic element content',
        legend_title_text=" ",
        legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01),
        barmode='group',
        template="plotly_white",
        font={'color': 'black', 'size': 30},
        xaxis = { 'linecolor': 'black', 'linewidth': 4,},
        yaxis = {'linecolor': 'black', 'linewidth': 4, 'range': [0.0, 1.0]}
        )
    pio.write_image(fig, "pic/non-metal.png")

# use 4270 binary or ternary samples, and 6316 all samples
def group_histogram2():
    x = np.array(['2', '3', '4', '5', '6', '7', '8', '>8',    '2', '3', '4', '5', '6', '7', '8', '>8'])
    y = [542, 1974, 1987, 1450, 906, 489, 276, 376,          622, 3648, 0., 0., 0., 0., 0., 0.]
    #y = [389, 1304, 1715, 1438, 1099, 710, 435, 908,         640, 3968, 772, 529, 260, 125, 14, 5]
    c = np.hstack((np.full(8, 'Generated'), np.full(8, 'Training')))
    # y1 = [389, 1304, 1715, 1438, 1099, 710, 435, 908]
    # y2 = [640, 3968, 772, 529, 260, 125, 14, 5]

    df = pd.DataFrame({'N-Alloy systems':x, 'Number of MG samples': y, "Type": c})
    fig = px.bar(data_frame=df,
                 #title="Sample size", # 图的标题
                 x='N-Alloy systems',
                 y='Number of MG samples', # y轴
                 color="Type",
                 width=1200, height=700,
                 barmode='group',
                 color_discrete_sequence=px.colors.qualitative.T10
                 )

    fig.update_layout(
       # title='Number of N-Component Alloy Systems',
        legend_title_text="",
        legend=dict(yanchor="top", y=0.99, xanchor="right", x=0.99),
        barmode='group',
        template="plotly_white",
        font={'color': 'black', 'size': 30},
        xaxis = { 'linecolor': 'black', 'linewidth': 4,},
        yaxis = {'linecolor': 'black', 'linewidth': 4, }
        )
    pio.write_image(fig, "pic/n-component-3.png")

def violin():
    #记得在ppt里边改成百分比...
    plt.figure(figsize=(12, 7))
    sns.set(context='paper', style='white', color_codes=True, font_scale=3)
    data = pd.read_csv('pic/violin-fe-al.csv')
    fig = sns.violinplot(x="Element", y="Percentage", hue="Data source",
                    split="True", data=data, palette='tab10')
    fig.legend(loc='upper right', title = "", fontsize = 25)
    fig.get_figure().savefig("pic/Fe-Al-vio.png", dpi = 400)
    ####################

    plt.figure(figsize=(12, 7))
    data = pd.read_csv('pic/violin-cuzr-mgal.csv')
    fig = sns.violinplot(x="Element", y="Percentage", hue="Data source",
                    split="True", data=data, palette='tab10')

    fig.legend(loc='upper right', title = "", fontsize = 25)
    fig.get_figure().savefig("pic/CuZr-MgAl-vio.png", dpi = 400)



def line():
    x = np.array([0.25,  0.5,   1,     3,     5,     10,     15,    20,    30,    40,    50,    60,
                  0.25,  0.5,   1,     3,     5,     10,     15,    20,    30,    40,    50,    60])
    y = np.array([1.0,   1.00,  1.00,  1.00,  1.00,  0.997,  0.997, 0.997, 0.997, 0.997, 0.997, 0.997,
                  0.641, 0.526, 0.438, 0.363, 0.331, 0.292,  0.26,  0.226, 0.198, 0.176, 0.1623, 0.1506])

    dsize = int(len(y)/2)
    c = np.hstack((np.full(dsize, 'Unique MG samples'), np.full(dsize, 'Unique alloy systems')))


    df = pd.DataFrame({'Generated samples(IE3)': x, 'Unique samples': y, "Type": c})
    fig = px.line(data_frame=df,
                 title="",  # 图的标题
                 x='Generated samples(IE3)',
                 y='Unique samples',  # y轴
                 color="Type",
                 markers="Type",
                 width=1200, height=700,
                 color_discrete_sequence=px.colors.qualitative.T10
                 )

    fig.update_layout(
        legend_title_text="",
        legend=dict(yanchor="top", y=0.86, xanchor="right", x=0.99),
        template="plotly_white",
        font={'color': 'black', 'size': 30},
        xaxis={'linecolor': 'black', 'linewidth': 4, },
        yaxis={'linecolor': 'black', 'linewidth': 4, }
    )
    pio.write_image(fig, "pic/line.png")


    # plt.figure(figsize=(12, 7))
    #plt.title(label)

    # x1 = np.array([0.25, 0.5, 1, 2, 3, 4, 5, 8, 15])
    # y1 = np.array([1.0, 1.00, 1.00, 1.00, 1.00, 0.997, 0.997, 0.995, 0.991])
    # x2 = np.array([0.25, 0.5, 1, 2, 3, 4, 5, 8, 15])
    # y2 = np.array([0.641, 0.526, 0.398, 0.323, 0.291, 0.26, 0.226, 0.20, 0.161])
    # # x3 = np.array([0.25, 0.5, 1, 2, 3, 4])
    # # y3 = np.array([0.641, 0.526, 0.398, 0.932, 0.933, 0.89])
    #
    # plt.xlabel("Generated samples(IE3)", size=32, )
    # plt.ylabel("Unique samples", size=32, )
    # plt.plot(x1, y1, '.-', label='Unique alloys')
    # plt.plot(x2, y2, '.-', label='Unique alloy systems')
    #
    # plt.legend(loc='upper left', fontsize=26)
    # plt.savefig('pic/noval.png', bbox_inches='tight')
    # plt.show()
    
def main():
    line()
    # group_histogram1()
    #group_histogram2()
    #violin()


if __name__ == '__main__':
    main()